from flask import Blueprint
from flask import request, jsonify
from blog.appone.models import Post, Comment
from blog.appone.schema import PostSchema, CommentSchema
from blog.baseview import APIView
import time
import redis

r = redis.Redis(host='127.0.0.1', port=6379,db=0)
# pipe = r.pipeline(transaction=True)


blueprint = Blueprint('post', __name__)

# class myview(APIView):
#     pass
#
# myview.register_api(blueprint)

post_schema = PostSchema()
comment_schema = CommentSchema()


class CommentAPIView(APIView):
    model = Comment
    schema = comment_schema
    name = 'comments'
    path = '/comments'

    def get_query(self, advanced_conditions=None, q=None, session=None, *args, **kwargs):
        """ 默认获取查询方法, 子类可覆盖本方法实现自定义过滤

            Nested API需要自定义此方法
        """
        query = super(CommentAPIView, self).get_query(self, advanced_conditions, q, session, *args, **kwargs)
        posts_pk = kwargs.get('posts_pk')
        if posts_pk is not None:
            query = query.filter(self.model.post_id == posts_pk)
        return query


class PostAPIView(APIView):
    model = Post
    schema = post_schema
    name = 'posts'
    path = '/posts'
    nested_views = [CommentAPIView]


blueprint = Blueprint(name='post', import_name=__name__, url_prefix='/api')
blueprint.description = u'blogDemo'
PostAPIView.register_to(blueprint)
# CommentAPIView.register_to(blueprint)

@blueprint.route('/random_data', methods=['GET'])
def random_data():
    # for i in range(0,100):
    #     data = ''.join(random.sample(total, 10))
    #     print(data)
    #     tmp = Post(title='rabdom%d'%i, content=data)
    #     db.session.add(tmp)
    # posts = Post.query.all()
    # for post in posts:
    #     for i in range(0,random.randint(1,5)):
    #         data = ''.join(random.sample(total, 10))
    #         tmp = Comment(email='test.com', post_id=post.id, content=data)
    #         db.session.add(tmp)
    # db.session.commit()
    comments = Comment.query.all()
    for comment in comments:
        r.hset(comment.post_id, comment.id, comment)
    return jsonify({'data': 'done'})